package com.dap.configuration.web.config.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.json.ValueVo;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.utils.ConfigUtils;
import com.baidu.disconf.web.web.config.controller.ConfigFetcherController;
import com.baidu.disconf.web.web.config.dto.ConfigFullModel;
import com.baidu.disconf.web.web.config.validator.ConfigValidator4Fetch;
import com.baidu.dsp.common.annotation.NoAuth;
import com.baidu.dsp.common.constant.WebConstants;
import com.baidu.dsp.common.exception.DocumentNotFoundException;
import com.baidu.dsp.common.exception.FieldException;
import com.dap.configuration.service.config.form.ConfExtensionForm;
import com.dap.configuration.service.config.service.ConfigFetchExtensionMgr;

/**
 * 配置获取Controller, Disconf-client专门使用的
 *
 * @author dengxiang
 * @version 2014-6-16
 */
@Controller
@RequestMapping(WebConstants.API_PREFIX + "/configExtension")
public class ConfigFetchExtensionController {

	private static final Logger LOG = LoggerFactory
			.getLogger(ConfigFetcherController.class);


	@Autowired
	private ConfigValidator4Fetch configValidator4Fetch;

	@Autowired
	private ConfigFetchExtensionMgr configFetchExtensionMgr;

	/**
	 * 获取配置项 Item
	 *
	 * @param confForm
	 *
	 * @return
	 * @throws ConfigException 
	 */
	@NoAuth
	@RequestMapping(value = "/item", method = RequestMethod.GET)
	@ResponseBody
	public ValueVo getItem(ConfExtensionForm confForm) {
			// 校验
			ConfigFullModel configModel = null;
			try {
				if(StringUtils.isEmpty(confForm.getBankKey())){
					throw new Exception("bankKey不能为空");
				}
				if(StringUtils.isEmpty(confForm.getEnv())){
					throw new Exception("env不能为空");
				}
				configModel = configValidator4Fetch.verifyConfForm(confForm);
			} catch (Exception e) {
				LOG.error(e.getMessage(),e);
				return ConfigUtils.getErrorVo(e.getMessage());
			}

			return configFetchExtensionMgr.getConfItemByParameter(configModel
					.getApp().getId(), configModel.getEnv().getId(),
					configModel.getVersion(), configModel.getKey(), confForm
							.getBankKey());
	}

	/**
	 * 获取配置文件
	 *
	 * @return
	 * @throws ConfigException 
	 */
	@NoAuth
	@RequestMapping(value = "/file", method = RequestMethod.GET)
	@ResponseBody
	public HttpEntity<byte[]> getFile(ConfExtensionForm confForm)
			{
			boolean hasError = false;
			// 校验
			ConfigFullModel configModel = null;
			try {
				if(StringUtils.isEmpty(confForm.getBankKey())){
					throw new Exception("bankKey不能为空");
				}
				if(StringUtils.isEmpty(confForm.getEnv())){
					throw new Exception("env不能为空");
				}
				configModel = configValidator4Fetch.verifyConfForm(confForm);
			} catch (Exception e) {
				LOG.error(e.toString());
				hasError = true;
			}
			if (hasError == false) {
				try {
					Config config = configFetchExtensionMgr.getConfByParameter(
							configModel.getApp().getId(), configModel.getEnv()
									.getId(), configModel.getVersion(),
							configModel.getKey(), confForm.getBankKey(),
							DisConfigTypeEnum.FILE);
					if (config == null) {
						hasError = true;
						throw new DocumentNotFoundException(
								configModel.getKey());
					}

					return downloadDspBill(configModel.getKey(),
							config.getValue());

				} catch (Exception e) {
					LOG.error(e.toString());
				}
			}

			if (confForm.getKey() != null) {
				throw new DocumentNotFoundException(confForm.getKey());
			} else {
				throw new DocumentNotFoundException("");
			}
	}

	/**
	 * 下载
	 * @param fileName
	 *
	 * @return
	 * @throws ConfigException 
	 */
	public HttpEntity<byte[]> downloadDspBill(String fileName, String value)
			{
			HttpHeaders header = new HttpHeaders();
			byte[] res = null;
			if(StringUtils.isEmpty(value)){
				res = "".getBytes();
			}else{
				res = value.getBytes();
			}
			 
			String name = null;
			try {
				name = URLEncoder.encode(fileName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new FieldException("config", "文件名称转码出错", null);
			}
			header.set("Content-Disposition", "attachment; filename=" + name);
			header.setContentLength(res.length);
			return new HttpEntity<byte[]>(res, header);
	}

}
